package com.utils;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bean.PayNo;
import com.ophiux.wechat.model.OrderQueryResponse;
import com.ophiux.wechat.model.Refund;
import com.ophiux.wechat.utils.XmlUtil;
import com.utils.http.HttpClientConnectionManager;


public class GetWxOrderno
{
  public static DefaultHttpClient httpclient;
  private static Logger logger = LoggerFactory.getLogger(GetWxOrderno.class);

  static
  {
    httpclient = new DefaultHttpClient();
    httpclient = (DefaultHttpClient)HttpClientConnectionManager.getSSLInstance(httpclient);
  }


  public static PayNo getPayNo(String url,String xmlParam){
	  DefaultHttpClient client = new DefaultHttpClient();
	  client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	  HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	  String prepay_id = "";
	  String return_code="";
	  String result_code="";
	  String err_code_des="";
	  PayNo payNo=new PayNo();
      try{
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 HttpResponse  response=httpclient.execute(httpost);;
	     String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
	     System.out.println(jsonStr);
	     System.out.println("-----------------------------------");
	     XmlUtil xm=new XmlUtil();
	     return_code=xm.getValue(jsonStr, "return_code");
	     if(return_code.equals("FAIL")){
	    	 String return_msg=xm.getValue(jsonStr,"return_msg");
	    	 err_code_des=return_msg;
	    	 logger.info("错误原因!"+return_msg);
	     }else{
	    	 result_code=xm.getValue(jsonStr, "result_code");
		     if(return_code.equals("SUCCESS") && result_code.equals("SUCCESS")){
		    	 prepay_id=xm.getValue(jsonStr, "prepay_id");
		     }else{
		    	 err_code_des=xm.getValue(jsonStr,"err_code_des");
		     }
	     }
	     System.out.println("result_code="+result_code);
	     System.out.println("return_code="+return_code);
	     System.out.println("prepay_id="+prepay_id);
	     System.out.println("err_code_des="+err_code_des);
	     System.out.println("-----------------------------------");
	     payNo.setErrCodeDes(err_code_des);
	     payNo.setPrepayId(prepay_id);
	} catch (Exception e) {
		e.printStackTrace();
	}finally {
		httpost.abort();
		httpost.releaseConnection();
	}
	return payNo;
  }
  
  public static Refund getWxRefund(String url,String xmlParam){
	  String return_code="";
	  String err_code_des="";
	  String result_code="";
	  Refund reFund=new Refund();
      try{
	     String jsonStr =HttpClientConnectionManager.getPostMethodSSL(url,xmlParam);
	     System.out.println(jsonStr);
	     System.out.println("-----------------------------------");
	     XmlUtil xm=new XmlUtil();
	     return_code=xm.getValue(jsonStr, "return_code");
	     if(return_code.equals("FAIL")){
	    	 String return_msg=xm.getValue(jsonStr,"return_msg");
	    	 reFund.setErr_code_des(return_msg);
	    	 logger.info("错误原因!"+return_msg);
	     }else{
	    	 result_code=xm.getValue(jsonStr, "result_code");
		     if(return_code.equals("SUCCESS") && result_code.equals("SUCCESS")){
		    	 reFund.setResult_code(result_code);
		    	 reFund.setReturn_code(return_code);
	    		 String return_msg=xm.getValue(jsonStr, "return_msg");
	    		 reFund.setReturn_msg(return_msg);
	    		 String appid=xm.getValue(jsonStr, "appid");
	    		 reFund.setAppid(appid);
	    		 String mch_id=xm.getValue(jsonStr, "mch_id");
	    		 reFund.setMch_id(mch_id);
	    		// String sub_mch_id=xm.getValue(jsonStr, "sub_mch_id");
	    	//	 reFund.setSub_mch_id(sub_mch_id);
	    		 String nonce_str=xm.getValue(jsonStr, "nonce_str");
	    		 reFund.setNonce_str(nonce_str);
	    		 String sign=xm.getValue(jsonStr, "sign");
	    		 reFund.setSign(sign);
	    		 String transaction_id=xm.getValue(jsonStr, "transaction_id");
	    		 reFund.setTransaction_id(transaction_id);
	    		 String out_trade_no=xm.getValue(jsonStr, "out_trade_no");
	    		 reFund.setOut_trade_no(out_trade_no);
	    		 String out_refund_no=xm.getValue(jsonStr, "out_refund_no");
	    		 reFund.setOut_refund_no(out_refund_no);
	    		 String refund_id=xm.getValue(jsonStr, "refund_id");
	    		 reFund.setRefund_id(refund_id);
	    		 String refund_channel=xm.getValue(jsonStr, "refund_channel");
	    		 reFund.setRefund_channel(refund_channel);
	    		 String refund_fee=xm.getValue(jsonStr, "refund_fee");
	    		 reFund.setRefund_fee(refund_fee);
	    		 String coupon_refund_fee=xm.getValue(jsonStr, "coupon_refund_fee");
	    		 reFund.setCoupon_refund_fee(coupon_refund_fee);
	    		 String total_fee=xm.getValue(jsonStr, "total_fee");
	    		 reFund.setTotal_fee(total_fee);
	    		 String cash_fee=xm.getValue(jsonStr, "cash_fee");
	    		 reFund.setCash_fee(cash_fee);
	    		 String coupon_refund_count=xm.getValue(jsonStr, "coupon_refund_count");
	    		 reFund.setCoupon_refund_count(coupon_refund_count);
	    		 String cash_refund_fee=xm.getValue(jsonStr, "cash_refund_fee");
	    		 reFund.setCash_refund_fee(cash_refund_fee);
		     }else{
		    	 err_code_des=xm.getValue(jsonStr,"err_code_des");
		    	 reFund.setErr_code_des(err_code_des);
		     }
	    	 
	     }
	     System.out.println("return_code="+return_code);
	     System.out.println("result_code="+result_code);
	     System.out.println("err_code_des="+err_code_des);
	     System.out.println("-----------------------------------");
	} catch (Exception e) {
		e.printStackTrace();
	}
	return reFund;
	
  }
  
  public static OrderQueryResponse getOrderQu(String url,String xmlParam){
	  DefaultHttpClient client = new DefaultHttpClient();
	  client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	  HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	  String return_code="";
	  String result_code="";
	  //String err_code_des=""; //错误代码
	  String trade_state="";  //交易状态
	  //String trade_state_desc=""; //交易状态描述
	  String appid="";
 	  String mch_id ="";
 	  String sub_appid="";
 	  String sub_mch_id ="";
 	  String nonce_str="";
 	  String sign ="";
 	 // String err_code="";
	  OrderQueryResponse order=new OrderQueryResponse();
	  
      try{
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 HttpResponse  response=httpclient.execute(httpost);;
	     String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
	     System.out.println(jsonStr);
	     System.out.println("-----------------------------------");
	     XmlUtil xm=new XmlUtil();
	     return_code=xm.getValue(jsonStr, "return_code");
	     
	     if(return_code.equals("FAIL")){
	    	 String return_msg=xm.getValue(jsonStr,"return_msg");
	    	 order.setErr_code_des(return_msg);
	    	 logger.info("错误原因!"+return_msg);
	     }else{
	    	 result_code=xm.getValue(jsonStr, "result_code");
		     if(return_code.equals("SUCCESS") && result_code.equals("SUCCESS")){
		    	// err_code_des=xm.getValue(jsonStr, "err_code_des");
		    	// trade_state_desc=xm.getValue(jsonStr, "trade_state_desc");
		    	 appid=xm.getValue(jsonStr, "appid");
		    	 mch_id=xm.getValue(jsonStr, "mch_id");
		    	 sub_appid=xm.getValue(jsonStr, "sub_appid");
		    	 sub_mch_id=xm.getValue(jsonStr, "sub_mch_id");
		    	 nonce_str=xm.getValue(jsonStr, "nonce_str");
		    	 sign=xm.getValue(jsonStr, "sign");
		    	// err_code=xm.getValue(jsonStr, "err_code");
		    	 return_code=xm.getValue(jsonStr, "return_code");
		    	 String return_msg=xm.getValue(jsonStr, "return_msg");
		    	 String openid=xm.getValue(jsonStr, "openid");
		    	 String is_subscribe=xm.getValue(jsonStr, "is_subscribe");
		    	 String sub_is_subscribe=xm.getValue(jsonStr, "sub_is_subscribe");
		    	 String  trade_type=xm.getValue(jsonStr, "trade_type");
		    	 String  bank_type=xm.getValue(jsonStr, "bank_type");
		    	 String  total_fee=xm.getValue(jsonStr, "total_fee");
		    	 String transaction_id=xm.getValue(jsonStr, "transaction_id");
		    	 String  out_trade_no=xm.getValue(jsonStr, "out_trade_no");
		    	 String  time_end=xm.getValue(jsonStr, "time_end");
		    	 //order.setErr_code_des(err_code_des);
		    	 //order.setTrade_state_desc(trade_state_desc);
		    	 order.setAppid(appid);
		    	 order.setMch_id(mch_id);
		    	 order.setSub_appid(sub_appid);
		    	 order.setSub_mch_id(sub_mch_id);
		    	 order.setNonce_str(nonce_str);
		    	 order.setSign(sign);
		    	 //order.setErr_code(err_code);
		    	 order.setReturn_code(return_code);
		    	 order.setReturn_msg(return_msg);
		    	 order.setOpenid(openid);
		    	 order.setIs_subscribe(is_subscribe);
		    	 order.setSub_is_subscribe(sub_is_subscribe);
		    	 order.setTrade_type(trade_type);
		    	 order.setBank_type(bank_type);
		    	 order.setTotal_fee(total_fee);
		    	 order.setTransaction_id(transaction_id);
		    	 order.setOut_trade_no(out_trade_no);
		    	 order.setTime_end(time_end);
		     }else{
		    	 appid=xm.getValue(jsonStr,"appid");
		    	 mch_id =xm.getValue(jsonStr,"mch_id");
		    	 sub_appid=xm.getValue(jsonStr,"sub_appid");
		    	 sub_mch_id =xm.getValue(jsonStr,"sub_mch_id");
		    	 nonce_str=xm.getValue(jsonStr,"nonce_str");
		    	 sign =xm.getValue(jsonStr,"sign");
		    	 result_code=xm.getValue(jsonStr,"result_code");
		    	 //err_code=xm.getValue(jsonStr,"err_code");
		    	 //err_code_des=xm.getValue(jsonStr,"err_code_des");
		    	 order.setAppid(appid);
		    	 order.setMch_id(mch_id);
		    	 order.setSub_appid(sub_appid);
		    	 order.setSub_mch_id(sub_mch_id);
		    	 order.setNonce_str(nonce_str);
		    	 order.setSign(sign);
		    	 order.setResult_code(result_code);
		    	// order.setErr_code(err_code);
		    	// order.setErr_code_des(err_code_des);
		     }
	    	 
	     }
	     System.out.println("result_code="+result_code);
	     System.out.println("return_code="+return_code);
	   //  System.out.println("err_code_des="+err_code_des);
	     System.out.println("trade_state="+trade_state);
	    // System.out.println("trade_state_desc="+trade_state_desc);
	     System.out.println("-----------------------------------");
	} catch (Exception e) {
		e.printStackTrace();
	}finally {
		httpost.abort();
		httpost.releaseConnection();
	}
	return order;
  }
  
  /**
   *description:获取扫码支付连接
   *@param url
   *@param xmlParam
   *@return
   * @author zengjian
   * @see
   */
  public static String getCodeUrl(String url,String xmlParam){
	  DefaultHttpClient client = new DefaultHttpClient();
	  client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	  HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	  String code_url = "";
     try {
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 HttpResponse response = httpclient.execute(httpost);
	     String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
	    if(jsonStr.indexOf("FAIL")!=-1){
	    	return code_url;
	    }
	    Map map = doXMLParse(jsonStr);
	    code_url  = (String) map.get("code_url");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return code_url;
  }
  
  /**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParse(String strxml) throws Exception {
		if(null == strxml || "".equals(strxml)) {
			return null;
		}
		
		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if(children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}
			
			m.put(k, v);
		}
		
		//关闭流
		in.close();
		
		return m;
	}
	/**
	 * 获取子结点的xml
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if(!children.isEmpty()) {
			Iterator it = children.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if(!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		
		return sb.toString();
	}
  public static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}
  
}